import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { getStorage } from '@/utils/tools'
import router from "../router/index";
import { Result } from "@/types";

export const request = (options: any,isAllow = true ) => {
    return new Promise<Result>((resolve, reject) => {
        const service = axios.create({
            baseURL: import.meta.env.VITE_BASE_URL + 'sys/', // api 的 base_url
            timeout: 80000,
        })
        // axios.defaults.withCredentials = true;

        service.interceptors.request.use(
            (config: AxiosRequestConfig) => {
                if (!config.headers) {
                    throw new Error(
                        `Expected 'config' and 'config.headers' not to be undefined`
                    );
                }
                let token: string | unknown = getStorage('token');
                if (token && isAllow) {
                    config.headers['Authori-zation'] = 'Bearer ' + token
                }
                return config
            }, error => {
                Promise.reject(error)
            }
        )
        service.interceptors.response.use(
            (response: AxiosResponse) => {
                // console.log("成功，请求结果：",response)
                if (response.data.code === 700) {
                    router.replace({
                        path:"/login",
                        query: {
                            redirect: router.currentRoute.value.fullPath
                        }
                    });
                }
                if (response.data.code === 700) {
                    return Promise.reject({
                        data: response.data,
                        code: 'ERRPR_AUTH'
                    });
                }else if (response.data.code !== 1) {
                    return Promise.reject({
                        data: response.data,
                        code: 'ERRPR'
                    });
                }
                return Promise.resolve(response.data)
            },
            error => {
                // console.log("失败，请求结果：",error)
                return Promise.reject({
                    data: error.response.data,
                    code: 'SERVER_ERRPR'
                })
            }
        )
        // 请求处理
        service(options).then((res:any) => {
            resolve(res)
        }).catch(res => {
            if (res) reject(res)
        })
    })
}


export default request